package cn.neosoft.apigateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 利用google guava框架进行限流的操作 主要是实现ZuulFilter接口 并且设置类型为PRE_TYPE 且执行order优先级为最小 -4 代表优先级最高  经过判断需要限流的方法服务 进行判断
 */
@Component
public class RateLimiteFilter extends ZuulFilter {

    //每秒生成1000个令牌
    public static final RateLimiter RATE_LIMITER=RateLimiter.create(1000);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -4;
    }

    @Override
    public boolean shouldFilter() {
        //request
        RequestContext requestContent = RequestContext.getCurrentContext();
        HttpServletRequest request=requestContent.getRequest();

        //gateway/order/api/v1/order/save
        //http://localhost:9000/gateway/order/api/v1/order/save

        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());

        //只有gateway/order/api/v1/order/save 时使这个生效
        if("/gateway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Object run() throws ZuulException {
        //request
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取令牌
        //RATE_LIMITER.tryAcquire();
        //如果没有获取到令牌的话不能f访问 使用的时google guava限流方案
        if(!RATE_LIMITER.tryAcquire()){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
        }

        return null;
    }
}
